package com.eight.cloud.auth.model.vo;

import cn.hutool.core.util.ObjectUtil;
import com.eight.cloud.core.global.model.LoginUser;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName: CurrentUser
 * @Author: TXC
 * @Date: 2024-10-19 14:23
 **/
@Data
@AllArgsConstructor
public class CurrentUser implements UserDetails {
    /**
     * 当前用户
     */
    private LoginUser userDetail;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        if (ObjectUtil.isNotNull(this.userDetail)) {
            Set<SimpleGrantedAuthority> uniqueAuthorities = this.userDetail.getRoles().stream()
                    .flatMap(role -> role.getPermissions().stream().filter(ObjectUtil::isNotNull))
                    .map(permission -> new SimpleGrantedAuthority(permission.getCode()))
                    .collect(Collectors.toSet());
            authorities.addAll(uniqueAuthorities);
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return this.userDetail.getPassword();
    }

    @Override
    public String getUsername() {
        return this.userDetail.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
